import {
  login,
  logout,
} from '@/api/user'
import { setToken, getToken } from '@/libs/util'
import {localClear, localRead, localSave} from "../../libs/util";

export default {
  state: {
    userName: '',
    userId: '',
    avatarImgPath: '',
    token: getToken(),
    access: '',
    user_data: !localRead("user_data") ? '' : JSON.parse(localRead("user_data"))
  },
  mutations: {
    setAvatar(state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId(state, id) {
      state.userId = id
    },
    setUserName(state, name) {
      state.userName = name
    },
    setAccess(state, access) {
      state.access = access
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUser(state,user) {
      state.user_data = user
      localSave("user_data", JSON.stringify(user))
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin({commit}, {userName, password, verifyCode}) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password,
          verifyCode
        }).then(res => {
          const data = res.data
          commit('setToken', data.token)
          commit('setAvatar', data.avatar)
          commit('setUserName', data.userName)
          commit('setUserId', data.id)
          commit('setAccess', data.access)
          commit('setUser', data)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({state, commit}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          localClear()
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    }
  }
}
